package com.erps.CommonUtils;

import java.lang.reflect.Field;

public class BeanUtil {

	public static String getInsertSQL(String cTableName, Object obj) {
		try {
			Class<? extends Object> c = obj.getClass();
			// 获取所有的字段
			Field[] fields = c.getDeclaredFields();
			// 获取实体的类名，需与表名一致
			// 生成INSERT INTO table(field1,field2) 部分
			StringBuffer sbField = new StringBuffer();
			// 生成VALUES('value1','value2') 部分
			StringBuffer sbValue = new StringBuffer();
			sbField.append("insert into " + cTableName.toLowerCase() + "(");
			int fieldLength = fields.length;
			for (int i = 0; i < fieldLength; i++) {
				fields[i].setAccessible(true);
				sbField.append(fields[i].getName().toLowerCase() + ',');
				if (fields[i].get(obj) != null)
					sbValue.append("'" + fields[i].get(obj).toString() + "',");
				else
					sbValue.append("null,");
			}
			return sbField
					.replace(sbField.length() - 1, sbField.length(),
							") VALUES(")
					.append(sbValue.replace(sbValue.length() - 1,
							sbValue.length(), ");")).toString();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		}
		return null;
	}

	public static String getUpdateSQL(String cTableName, Object obj,
			String cWhereParm) {
		try {
			Field[] fields = obj.getClass().getDeclaredFields();
			StringBuffer sb = new StringBuffer();
			sb.append("UPDATE" + cTableName.toLowerCase() + "SET");
			int fieldLength = fields.length;
			for (int i = 0; i < fieldLength; i++) {
				fields[i].setAccessible(true);
				sb.append(fields[i].getName() + "= '" + fields[i].get(obj)
						+ "',");
			}
			return sb.replace(sb.length() - 1, sb.length(), "").toString()
					+ " " + cWhereParm;
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		}
		return null;
	}
}